package cn.adelyn.base.secureweb.config;

import cn.adelyn.base.secureweb.adapter.AuthConfigAdapter;
import cn.adelyn.base.secureweb.adapter.DefaultAuthConfigAdapterImpl;
import cn.adelyn.base.secureweb.filter.WebAuthFilter;
import cn.hutool.core.util.ArrayUtil;
import jakarta.servlet.DispatcherType;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @Author chengzelee
 * @Date 2022/11/27 16:29
 * @Desc 授权配置
 */
@Configuration
public class AuthConfig {

	@Bean
	@ConditionalOnMissingBean // 判断需要注入 Spring 容器中的 bean interface 的实现是否已经存在，有的话不注入，没有就注入
	public AuthConfigAdapter authConfigAdapter() {
		return new DefaultAuthConfigAdapterImpl();
	}

	@Bean
	public FilterRegistrationBean<WebAuthFilter> filterRegistration(AuthConfigAdapter authConfigAdapter, WebAuthFilter webAuthFilter) {
		FilterRegistrationBean<WebAuthFilter> registration = new FilterRegistrationBean<>();
		// 添加过滤器
		registration.setFilter(webAuthFilter);
		// 设置过滤路径，/*所有路径
		registration.addUrlPatterns(ArrayUtil.toArray(authConfigAdapter.filterPathPatterns(), String.class));
		registration.setName("authFilter");
		// 设置优先级
		registration.setOrder(0);
		// 设置过滤的请求类型
		registration.setDispatcherTypes(DispatcherType.REQUEST);
		return registration;
	}

}
